package com.neusoft.neuiotms.dcam.workflow.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.persistence.EntityNotFoundException;
import javax.transaction.Transactional;

import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.activiti.dto.ProcessInstanceDTO;
import com.neusoft.bizcore.activiti.service.ProcessInstanceService;
import com.neusoft.bizcore.activiti.service.WorkOrderService;
import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.neuiotms.dcam.anhui.itsm.WorkflowBean;
import com.neusoft.neuiotms.dcam.constant.DCAMConsts;
import com.neusoft.neuiotms.dcam.fixed.dto.AssetLifeCycleDTO;
import com.neusoft.neuiotms.dcam.fixed.model.Asset;
import com.neusoft.neuiotms.dcam.fixed.repository.AssetRepository;
import com.neusoft.neuiotms.dcam.fixed.service.AssetLifeCycleService;
import com.neusoft.neuiotms.dcam.fixed.service.AssetService;
import com.neusoft.neuiotms.dcam.fixed.service.ItsmService;
import com.neusoft.neuiotms.dcam.workflow.converter.ITSMApproveConverter;
import com.neusoft.neuiotms.dcam.workflow.converter.TuikuKJConverter;
import com.neusoft.neuiotms.dcam.workflow.dto.ITSMApproveDTO;
import com.neusoft.neuiotms.dcam.workflow.dto.TuikuItemKJDTO;
import com.neusoft.neuiotms.dcam.workflow.dto.TuikuKJDTO;
import com.neusoft.neuiotms.dcam.workflow.model.ITSMApprove;
import com.neusoft.neuiotms.dcam.workflow.model.TuikuItemKJ;
import com.neusoft.neuiotms.dcam.workflow.model.TuikuKJ;
import com.neusoft.neuiotms.dcam.workflow.repository.ITSMApproveRepository;
import com.neusoft.neuiotms.dcam.workflow.repository.TuikuItemKJRepository;
import com.neusoft.neuiotms.dcam.workflow.repository.TuikuKJRepository;
import com.neusoft.neuiotms.dcam.workflow.service.TuikuKJService;

import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class TuikuKJServiceImpl implements TuikuKJService {

    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private ProcessInstanceService processInstanceService;
    @Autowired
    private TuikuKJRepository tuikuKJRepository;
    @Autowired
    private TuikuItemKJRepository tuikuItemKJRepository;
    @Autowired
    private TuikuKJConverter tuikuKJConverter;
    @Autowired
    private ITSMApproveRepository approveRepository;
    @Autowired
    private ITSMApproveConverter approveConverter;
    @Autowired
    private AssetRepository assetRepository;
    @Autowired
    private AssetService assetService;
    @Autowired
    private AssetLifeCycleService assetLifeCycleService;
    @Autowired
    private ItsmService itsmService;

    @Override
    @Transactional
    public TuikuKJDTO create(final TuikuKJDTO dto, final UserBean user) {

        final String taskId = dto.getTaskId();
        final ProcessInstanceDTO instance =
                this.workOrderService.submit(dto.getTitle(), DCAMConsts.PROCESSS_TUIKU_KJ_KEY, dto.getWorkOrderNum(),
                        user);
        dto.setTaskId(instance.getTaskId());
        dto.setWorkOrderNum(instance.getWorkorderNum());
        dto.setCreateUser(user.getUsername());
        dto.setCreateUserName(user.getName());

        // 查询当前workOrderNum和TaskId下是否存在记录
        final TuikuKJ oldModel = this.tuikuKJRepository.findByWorkOrderNumAndTaskId(
                dto.getWorkOrderNum(), taskId);
        if (oldModel == null) {
            dto.setId(null);
        }

        // 解锁以前的资产信息
        final List<TuikuItemKJ> all = this.tuikuItemKJRepository.findByMain_WorkOrderNum(dto.getWorkOrderNum());
        if (null != all) {
            this.assetService.updateLocked(all.stream().map(l -> l.getCode()).distinct().collect(Collectors.toList()),
                    false);
        }

        TuikuKJ model = this.tuikuKJConverter.toModel(dto);
        model = this.tuikuKJRepository.save(model);

        // 完成当前节点
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);

        try {
            // 对接ITSM
            final List<WorkflowBean.AssetBean> assetList = Lists.newArrayList();
            for (final TuikuItemKJDTO item : dto.getStockBackDetail()) {
                final WorkflowBean.AssetBean assetBean = WorkflowBean.AssetBean.builder()
                        .assetId(item.getCode())
                        .assetClassID(item.getSmallTypeCode())
                        .assetModel(item.getSpecifications())
                        .assetUnit("未知")
                        .assetPrice(0)
                        .assetNumber(1)
                        .assetName(item.getName())
                        .assetType("1")
                        .assetSign("未知")
                        .build();
                assetList.add(assetBean);
            }

            final WorkflowBean workflowBean = WorkflowBean.builder()
                    .workNum(dto.getWorkOrderNum())
                    .workName("设备退库")
                    .workType("30")
                    .workContent("设备退库申请")
                    .applyUser(user.getUsername())
                    .assetList(assetList)
                    .build();

            this.itsmService.pushItsm(workflowBean);
        } catch (final Exception e) {
            TuikuKJServiceImpl.log.error("设备退库流程推送ITSM时发生错误", e);
        }

        final TuikuKJDTO result = this.tuikuKJConverter.toDTO(model);

        // 枷锁资产信息
        this.assetService.updateLocked(
                result.getStockBackDetail().stream().map(l -> l.getCode()).distinct().collect(Collectors.toList()),
                true);

        return result;
    }

    @Override
    public TuikuKJDTO detail(final String workOrderNum, final String taskId, final UserBean user) {
        TuikuKJ model = null;
        try {
            if (StringUtils.isNotBlank(workOrderNum) && !"NULL".equals(taskId)) {
                model = this.tuikuKJRepository.findByWorkOrderNumAndTaskId(workOrderNum, taskId);
                if (model == null) {
                    // 获取前一节点的TaskID
                    final String lastTaskId = this.processInstanceService.getLastTaskId(taskId, user);
                    if (lastTaskId == null) {
                        return new TuikuKJDTO();
                    } else {
                        model = this.tuikuKJRepository.findByWorkOrderNumAndTaskId(workOrderNum,
                                lastTaskId);
                    }
                }
            } else if ("NULL".equals(taskId)) {
                final List<TuikuKJ> TuikuKJs =
                        this.tuikuKJRepository.findAllByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
                if ((TuikuKJs != null) && (TuikuKJs.size() > 0)) {
                    model = TuikuKJs.get(0);
                }
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workOrderNum },
                    new Object[] {taskId });
        }
        return this.tuikuKJConverter.toDTO(model);
    }

    @Override
    @Transactional
    public ITSMApproveDTO itsmCreate(final ITSMApproveDTO dto, final UserBean user) {
        final ITSMApprove model = this.approveConverter.toModel(dto);
        this.approveRepository.save(model);
        this.processInstanceService.setGlobalVariable(dto.getTaskId(), DCAMConsts.PROCESSS_TUIKU_KJ_APPROVE_RESULT,
                dto.getResult());
        // 完成当前节点
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);

        return this.approveConverter.toDTO(model);
    }

    @Override
    public ITSMApproveDTO itsmDetails(final String workOrderNum, final String taskId, final UserBean user) {
        ITSMApprove model = null;
        try {
            if (StringUtils.isNotBlank(workOrderNum) && !"NULL".equals(taskId)) {
                model = this.approveRepository.findByWorkOrderNumAndTaskId(workOrderNum, taskId);
                if (model == null) {
                    // 获取前一节点的TaskID
                    final String lastTaskId = this.processInstanceService.getLastTaskId(taskId, user);
                    if (lastTaskId == null) {
                        return new ITSMApproveDTO();
                    } else {
                        model = this.approveRepository.findByWorkOrderNumAndTaskId(workOrderNum,
                                lastTaskId);
                    }
                }
            } else if ("NULL".equals(taskId)) {
                model =
                        this.approveRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workOrderNum },
                    new Object[] {taskId });
        }
        return this.approveConverter.toDTO(model);
    }

    @Override
    public TuikuKJDTO confrimCreate(final TuikuKJDTO dto, final UserBean user) {

        final List<TuikuItemKJ> models = dto.getStockBackDetail().stream().map(l -> {
            final TuikuItemKJ model = this.tuikuItemKJRepository.getOne(l.getId());
            model.setTuikuLocation(l.getTuikuLocation());
            model.setTuikuLocationName(l.getTuikuLocationName());
            return model;
        }).collect(Collectors.toList());

        this.tuikuItemKJRepository.saveAll(models);

        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);

        // 更新资产
        this.tuikuKJCompleteUpdate(dto);

        return dto;
    }

    @Override
    public TuikuKJDTO confrimDetail(final String workOrderNum, final String taskId, final UserBean user) {

        TuikuKJDTO dto = new TuikuKJDTO();

        final TuikuKJ model = this.tuikuKJRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
        if (null != model) {
            dto = this.tuikuKJConverter.toDTO(model);
        }

        return dto;
    }

    private void tuikuKJCompleteUpdate(final TuikuKJDTO dto) {
        final List<AssetLifeCycleDTO> lifeList = new ArrayList<>();
        final List<Asset> assets = dto.getStockBackDetail().stream().map(l -> {
            final Asset asset = this.assetRepository.findByCode(l.getCode());
            asset.setLocked(false);
            asset.setLocation(l.getTuikuLocation());
            asset.setLocationName(l.getTuikuLocationName());
            asset.setManagementOrgName(null);
            asset.setManagementOrgCode(null);
            asset.setManagementUserCode(null);
            asset.setManagementUserName(null);
            asset.setStatus(DCAMConsts.ASSET_STATUS_UNUSED);

            // 生命周期
            lifeList.add(AssetLifeCycleDTO.builder().code(asset.getCode())
                    .lifeCycle(DCAMConsts.ASSET_LIFE_TYPE_TUIKU)
                    .content(asset.getName() + "已退库").workNum(dto.getWorkOrderNum()).build());

            return asset;
        }).collect(Collectors.toList());

        if ((assets != null) && (assets.size() > 0)) {
            this.assetRepository.saveAll(assets);
        }

        if (lifeList.size() > 0) {
            this.assetLifeCycleService.batchCreate(lifeList);
        }

    }
}
